package lumis.service.group;

import org.w3c.dom.Node;

import lumis.doui.table.TableSource;
import lumis.doui.table.filter.TableSourceFilter;
import lumis.portal.PortalException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.util.query.IQueryFilter;
import lumis.util.query.IQueryValue;
import lumis.util.query.QueryValue;

/**
 * Filters according the custom property <code>domain</code> value.
 * 
 * @version $Revision: 10825 $ $Date: 2009-08-04 12:36:40 -0300 (Tue, 04 Aug 2009) $
 * @since 5.0.0
 */
public class DomainScopeFilter extends TableSourceFilter
{
	/**
	 * The value used to represent the global domain.
	 * @see #DOMAIN_CUSTOM_PROPERTY_NAME
	 * @since 5.0.0
	 */
	public static String GLOBAL_DOMAIN_VALUE = "lum_global";

	/**
	 * The name of the custom property used to store the domain.
	 * <p>
	 * For local domains, the value is the channel identifier, for all domains the value
	 * is <code>null</code>, and for global domain the value is {@link #GLOBAL_DOMAIN_VALUE}.
	 * 
	 * @see #GLOBAL_DOMAIN_VALUE
	 * 
	 * @since 5.0.0
	 */
	public static String DOMAIN_CUSTOM_PROPERTY_NAME = "domain";
	
	/**
	 * The domain this filter will use to filter the results. This value is read
	 * from the domain custom property ({@link #DOMAIN_CUSTOM_PROPERTY_NAME}).
	 *
	 * @see #DOMAIN_CUSTOM_PROPERTY_NAME
	 * @see #GLOBAL_DOMAIN_VALUE
	 * @since 5.0.0
	 */
	private String domain;
	
	@Override
	protected String calculateFilterOperator(Node filterNode) throws PortalException
	{
		// read domain
		TableSource source = getSource();
		String serviceInstanceId = source.getDouiContext().getRequest().getServiceInstanceConfig().getId();
		domain = ManagerFactory.getServiceInstanceManager().getCustomProperty(SessionConfig.getCurrentSessionConfig(), serviceInstanceId, 
				DOMAIN_CUSTOM_PROPERTY_NAME, source.getDouiContext().getTransaction());

		// If the domain is global sets operator filter to IQueryFilter.FILTER_OPERATOR_IS_NULL
		String calculateFilterOperator;
		if(GLOBAL_DOMAIN_VALUE.equals(this.domain))
			calculateFilterOperator = IQueryFilter.FILTER_OPERATOR_IS_NULL;
		else
			calculateFilterOperator = IQueryFilter.FILTER_OPERATOR_LIKE;
		
		return calculateFilterOperator;
	}
	
	@Override
	protected IQueryValue calculateFilterValue(Node filterNode) throws PortalException
	{
		// For compatibility reason if the domain is global sets null.
		if(this.domain == null || GLOBAL_DOMAIN_VALUE.equals(this.domain))
		{
			// domain == null, use filter "LIKE null", that will be discarded by super
			// domain == lum_global, use filter "IS NULL"
			return null;
		}
		else
		{
			// use filter "LIKE <domain>"
			return new QueryValue(this.domain);
		}
	}
	
}
